<template>
  <div class="menu-check">
    <el-input v-model="keyword" placeholder="输入关键字进行过滤" />
    <div class="menu-check__box">
      <el-tree
        ref="tree"
        :data="data"
        :props="defaultProps"
        :filter-node-method="filterNode"
        node-key="id"
        show-checkbox
      />
    </div>
  </div>
</template>

<script>
import { getMenuList } from "@/api/menu";
import { deepTree, isLeaf } from "@/utils";

export default {
  name: "menu-check",

  data() {
    return {
      // 关键字
      keyword: "",
      // menuList 数据
      list: [],

      defaultProps: {
        label: "name",
        children: "children",
      },
    };
  },

  computed: {
    // Tree组件需要的数据
    data() {
      // 转树形格式
      return deepTree(this.list);
    },
  },

  watch: {
    keyword(value) {
      this.$refs.tree.filter(value);
    },
  },

  methods: {
    refresh() {
      console.log("MenuCheck refresh");
      getMenuList().then((data) => {
        this.list = data;
        console.log("MenuCheck refresh then");
        // 通知父组件，我数据OK了。
        this.$emit("ok");
      });
    },

    /**
     * 过滤节点的函数
     * @param {*} value 过滤关键字，在调用 Tree 实例的 filter 方法时传递过来的参数
     * @param {*} data 节点数据，会让每个节点都执行该函数
     * @returns {boolean} 返回true，则表示当前节点需要显示，否则隐藏
     */
    filterNode(value, data) {
      // console.log("value", value);
      // console.log("data", data);
      // if (data.name === "label_2") {
      //   return true;
      // } else {
      //   return false;
      // }
      return data.name.includes(value);
    },

    /**
     * 获取当前勾选的Keys集合，包含选中与半选中
     */
    get() {
      //
      const key1 = this.$refs.tree.getCheckedKeys();
      const key2 = this.$refs.tree.getHalfCheckedKeys();
      return [...key1, ...key2];
    },

    /**
     * 设置当前勾选的Keys集合
     * NOTE:
     *    叶子节点 - 没有儿子的节点，就叫做叶子节点
     * PS: 要将非叶子节点给移除，避免勾选出问题
     *    1. [2, 3, 1]   => [2, 3]
     *    2. [6, 9, 10, 11, 12, 5]    => [9, 10, 11, 12]
     */
    set(keys) {
      console.log("MenuCheck set", this.list.length);
      const newKeys = keys.filter((id) => isLeaf(this.list, id));
      // console.log("newKeys", newKeys);
      this.$refs.tree.setCheckedKeys(newKeys);
    },

    fn1() {
      // getHalfCheckedKeys - 获取半选中
      // getCheckedKeys     - 获取选中
      console.log("getCheckedNodes", this.$refs.tree.getCheckedNodes());
      console.log("getCheckedKeys", this.$refs.tree.getCheckedKeys());
      console.log("getHalfCheckedKeys", this.$refs.tree.getHalfCheckedKeys());
    },

    fn2() {
      this.$refs.tree.filter("_2");
    },
  },

  created() {
    this.refresh();
  },
};
</script>

<style lang="scss" scoped>
.menu-check {
  width: 100%;
  &__box {
    margin-top: 10px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 5px 0;
    background-color: #fff;
  }
}
</style>
